/**
 * pool的souce处理模块，分析页面获取代理信息
 */
const debug = require('debug')('proxy-pool');

function ProxySource(name, func, pool) {
  this.name = name; 
  this._func = func;    // 获取proxy的函数
  this._pool = pool;    // proxy pool
  this._isRunning = false;
  this._interval = 60 * 1000;
  this._startTime = 0;  // 开始时间(ms)
  this._endTime = 0;    // 结束时间(ms)
}

/**
 * 启动source获取
 */
ProxySource.prototype.start = function() {
  debug("启动proxy source:", this.name);
  if(this._isRunning) {
    return true;
  }
  this._isRunning = true;
  this._tick(); 
  return true;
}

/**
 * 结束运行
 */
ProxySource.prototype.stop = async function () {
  this._isRunning = false;
}

/***********************************************
 * internal API
 ***********************************************/

/**
 * tick 逻辑
 */
ProxySource.prototype._tick = async function() {
  if (!this._isRunning) {
    return false;
  }
  this._startTime = +new Date;
  let isOk = await this._tickWork();
  this._endTime = +new Date;
  let timeuse = this._endTime - this._startTime;
  let timeInterval = Math.max(this._interval - timeuse, 500);
  // logger.debug("%s下次tick 时间：", this.name, timeInterval, " start:", this._startTime, " end:", this._endTime);
  setTimeout(this._tick.bind(this), timeInterval);
}

/**
 * 执行具体的tick逻辑
 */
ProxySource.prototype._tickWork = async function() {
  debug("执行source:%s tick", this.name);
  try {
    let data = await this._func();
    // debug("proxy list:", data);
    if(data && data.length > 0) {
      await this._pool.checkRoughProxys(data);
    }
    return true;
  } catch (error) {
    debug("%s 更新数据报错:", this.name);
    return false;
  }
}

exports = module.exports = ProxySource;